global._dirname = __dirname;
global._configPath = global._dirname + '/config.js';

const {execSyncS, execSyncGit} = require('./exec.js');
const fs = require('fs');
const {BASE_CONFIG} = require(global._configPath);
const {copyFile} = require('fs/promises');
const {OSSModel} = require('./OSSModel');
const os = require('os');

const startTime = new Date().getTime();
const editorPath = BASE_CONFIG['editorPath']
let shellGit = 'git';

/**
 * 上传图片到cdn
 * @param imgPath
 * @param webName
 */
 async function uploadToCdn(imgPath, webName, uploadBucket="tuguaishou-js") {
    console.log("upload file: ", imgPath);
    console.log("to: ", webName);
    let oss_client = new OSSModel(uploadBucket);
    oss_client.connection();

    let promise1 = async () => {
        return new Promise(async (resolve) => {
            resolve(await oss_client.uploadFile(webName, imgPath))
        })
    }

    for (let i = 0; i < 3; i++){
        let a1 = await promise1();
        isSuccess = 1;
        if( !a1 ){
            console.log("upload error");
            console.log(a1);
            isSuccess = 0;
        }
        if( isSuccess ){
            break;
        }
    }
    return isSuccess;
};

async function main() {
    console.log("step: 上传 js、css 资源到 CDN START");
    let uploadFilePathList = [];

    function readDirSync(path, subPath){
        let pa = fs.readdirSync(path + '/' + subPath);
        pa.forEach(function(ele, index){
            let info = fs.statSync(path + '/' + subPath + '/' + ele)	
            if(info.isDirectory()){
                console.log("dir: "+ele)
                readDirSync(path, subPath + "/" + ele);
            }else{
                uploadFilePathList.push({
                    filePath: subPath + '/' + ele
                });
                console.log("file: "+ subPath + '/' + ele)
            }	
        })
        console.log('异步文件读取！！！', pa, path, subPath)
    }
    readDirSync(BASE_CONFIG['prodPath'], BASE_CONFIG['uploadDir']); //editorPath

    uploadFilePathList.forEach(async (item) => {
        //editorPath
        await uploadToCdn(BASE_CONFIG['prodPath'] + item['filePath'], BASE_CONFIG['uploadCdnDir'] + item['filePath']);
    });
    console.log("step: 上传 js、css 资源到 CDN END");
}
main()
module.exports = {main}